const cloud = require('wx-server-sdk')

// 初始化 cloud
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV,
  throwOnNotFound: false
})
const db = cloud.database();
const _ = db.command;
const $ = _.aggregate;

/**
 * 这个示例将经自动鉴权过的小程序用户 openid 返回给小程序端
 * event 参数包含小程序端调用传入的 data
 */
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  let user = {
    openid: wxContext.OPENID,
    appid: wxContext.APPID,
    unionid: wxContext.UNIONID,
  };
  let where = {openid: user.openid}
  if(event.where&&event.where.uid){
    where = {uid:event.where.uid}
  }
  let userinfo = (await db.collection('user').where(where).get()).data;
  console.log(userinfo);
  if (!userinfo || userinfo.length == 0){
    //  await db.collection('user').add({
    //   data: {
    //     _id:user.openid,
    //     _openid:user.openid
    //   }
    // });
    return user;
  }
  userinfo = userinfo[0];
  userinfo.appid = user.appid;
  var team_user = (await db.collection('team').field({studioid: true, job: true}).where({openid: userinfo.openid, status: 1}).get()).data;
  let last_id = userinfo.studioid;
  if (last_id) {
    // 管理员要默认加到 team 中去！
    if (team_user.length == 0){
      // 表示用户不存在
      if (userinfo.studioid){
        delete userinfo.studioid;
      }
      return userinfo;
    }
  }

    for(var i =0 ;i < team_user.length; i++){
      last_id = team_user[i].studioid;
      userinfo.job = team_user[i].job;
      if (last_id == userinfo.studioid){
        break;
      }
    }
    // if (team_user.length > 0 && team_user.indexOf(userinfo.studioid) < 0){  // 如果用户不能登录当前工作室，则默认登录到可用的工作室
    //   userinfo.studioid = team_user[0].studioid;
    // }
  if (last_id){
    var studio = (await db.collection('studio').doc(last_id).get()).data;
    if (studio){
      userinfo.studio = studio;
      userinfo.studioid = last_id;
    }
    var orders = (await db.collection('order').aggregate().match({
      studioid:  userinfo.studioid
    }).group({
      _id: '$studioid',
      count: $.sum(1),
      amount: $.sum('$price')
    }).end()).list;
    // console.log(orders);
    userinfo.studio.orders = orders[0];
    userinfo.studio.customers = (await db.collection('customer').where({studioid: last_id}).count()).total;
  }
  
  return userinfo;
}